/**
 * 
 */
package com.p2p.front.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.p2p.front.dal.dao.TenderAutoQueueDao;
import com.p2p.front.dal.model.TenderAutoQueue;
import com.p2p.front.service.TenderAutoQueueService;

/**
 * @author ricky
 *
 */
@Service("tenderAutoQueueService")
public class TenderAutoQueueServiceImpl implements TenderAutoQueueService {

	@Resource
	TenderAutoQueueDao tenderAutoQueueDao;
	
	
	@Override
	public List<TenderAutoQueue> listAll() {
		// TODO Auto-generated method stub
		return tenderAutoQueueDao.listAll();
	}

	@Override
	public boolean inAutoQueue(String userId) {
		if(tenderAutoQueueDao.getByUserId(userId)!=null){
			return false;
		}
		TenderAutoQueue tenderAutoQueue = new TenderAutoQueue();
		tenderAutoQueue.setUserId(userId);
		try {
			tenderAutoQueueDao.create(tenderAutoQueue);
			return true;
		} catch (Exception e) {
			return false;
		}
		
	}

	@Override
	public boolean outAutoQueue(String userId) {
		return 1==tenderAutoQueueDao.remove(userId);
	}

	@Override
	public void refreshAutoQueueRank() {
		/*List<TenderAutoQueue> list = tenderAutoQueueDao.listAll();
		int i=0;
		for(TenderAutoQueue tenderAutoQueue:list){
			i++;
			tenderAutoQueue.setRank(i);
			tenderAutoQueueDao.updateRank(tenderAutoQueue);
		}*/
		
		tenderAutoQueueDao.cleanRank();
	}

	@Override
	public TenderAutoQueue getByUserId(String userId) {
		return tenderAutoQueueDao.getByUserId(userId);
	}

	@Override
	public Integer getMaxRank() {
		return tenderAutoQueueDao.getMaxRank();
	}

	@Override
	public Integer getRankIdByUserId(String userId) {
		TenderAutoQueue tenderAutoQueue = getByUserId(userId);
		if(tenderAutoQueue==null) {
			return null;
		} else {
			Integer rank = tenderAutoQueue.getRank();
			if(rank==null||rank==0) {
				String id = ""+tenderAutoQueue.getId();
				rank = tenderAutoQueueDao.getRankById(id);
				//更新数据库
				tenderAutoQueue.setRank(rank);
				tenderAutoQueueDao.updateRank(tenderAutoQueue);
			} 
			return rank;
		}
	}

	@Override
	public boolean checkInAutoQueueByUid(String userId) {
		if(tenderAutoQueueDao.getByUserId(userId)!=null){
			return true;
		} 
		return false;
	}

	
}
